package com.labor_management_system.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.labor_management_system.Entity.Payroll;
import com.labor_management_system.Service.EmployeeService;
import com.labor_management_system.Service.PayrollService;
import com.labor_management_system.Service.TeamService;
import com.labor_management_system.Utils.R;
import com.labor_management_system.Vo.PayrollVo;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/laborSettlement")
public class LaborSettlementController {
    //劳务结算管理
    @Autowired
    private PayrollService payrollService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询工资记录分页
     * @return
     */
//    private String ename;
//    //班组名称
//    private String tname;
//    //考勤月份
//    private Long attendanceDate;
//    @GetMapping("/page")
//    public R page(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, @RequestParam("employeeName")String employeeName,@RequestParam("teamName")String teamName,@RequestParam("attendanceDate")Long attendanceDate ){
//        IPage<Payroll> iPage = payrollService.sumPayroll(new Page<>(pageNum,pageSize),new PayrollVo(employeeName,teamName,attendanceDate));
//        for(Payroll payroll : iPage.getRecords()){
//            payroll.setEmployee(employeeService.getById(payroll.getEid()));
//            if(payroll.getEmployee()!=null){
//                payroll.setTname(teamService.getById(payroll.getEmployee().getTeamId()).getTeamName());
//            }
//        }
//        return R.ok().data("info", iPage);
//    }
    @PostMapping("/GET/page")
    public R page(Page page, PayrollVo payrollVo){
        IPage<Payroll> iPage = payrollService.sumPayroll(page,payrollVo);
        for(Payroll payroll : iPage.getRecords()){
            payroll.setEmployee(employeeService.getById(payroll.getEid()));
            if(payroll.getEmployee()!=null){
                payroll.setTname(teamService.getById(payroll.getEmployee().getTeamId()).getTeamName());
            }
        }
        return R.ok().data("info", iPage);
    }


    /**
     * 导出转excel
     * 将文件以数据流格式输出
     * @return
     */
    @RequestMapping("/GET/export")
    public void export(Page page, PayrollVo payrollVo) throws IOException {
        R promotionWord=page(page, payrollVo);
        Map<String, Object> promotionWordData =promotionWord.getData();
//        R result = (R) promotionWord.getData();
//        JSONObject jsonObject = new JSONObject();
////        jsonObject.put("success", result.getSuccess());
////        jsonObject.put("code", result.getCode());
////        jsonObject.put("message", result.getMessage());
//        jsonObject.put("data", new JSONObject(result.getData()));
        try {
            // 导出JSON数据到Excel文件
            exportJsonToExcel(promotionWordData, "D:\\360MoveData\\Users\\HP\\Desktop\\output.xlsx");
            System.out.println("JSON数据已成功导出到Excel文件");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将JSON数据导出到Excel文件
    public static void exportJsonToExcel(Map<String, Object> jsonObject, String filePath) throws Exception {

        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");


        // 创建表头
        Row headerRow = sheet.createRow(0);
        int columnIndex = 0;//表头标记

//            HSSFRow rowTtile = (HSSFRow) sheet.createRow(1000);

        // 遍历第一个JSON对象的键，作为Excel表头
        for (String key : jsonObject.keySet()) {
            Cell cell = headerRow.createCell(columnIndex++);//在columnIndex行创建一个新的单元格（Cell），并赋值
            cell.setCellValue(key);//将 JSON 数据中的键作为 Excel 表格的表头
        }

        // 填充数据
        int rowIndex = 1;

        Row dataRow =sheet.createRow(rowIndex++);
        columnIndex = 0;

        // 将JSON数据填充到Excel中
        for (String key : jsonObject.keySet()) {
            Cell cell = dataRow.createCell(columnIndex++);//在columnIndex行创建一个新的单元格（Cell），并赋值
            cell.setCellValue(jsonObject.get(key).toString());
        }

        // 保存Excel文件
        FileOutputStream fileOut = new FileOutputStream(filePath);
        workbook.write(fileOut);
        fileOut.close();

        workbook.close();
    }
}
